package hk.m4s.lr.repair.test.ui.equipment;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import framework.common.Constant;
import framework.common.alertview.AlertView;
import framework.common.alertview.OnItemClickListener;
import framework.common.baseui.UeBaseActivity;
import framework.common.takephoto.CustomHelper;
import framework.common.zanetwork.core.ResponseCallback;
import framework.utils.SharedPreferencesUtils;
import hk.m4s.lr.repair.test.R;
import hk.m4s.lr.repair.test.model.DeviceRepalyModel;
import hk.m4s.lr.repair.test.model.DeviceRepalyModelResult;
import hk.m4s.lr.repair.test.model.NoticeDeviceModel;
import hk.m4s.lr.repair.test.model.NoticeDeviceModelResult;
import hk.m4s.lr.repair.test.service.device.DeviceListervice;
import hk.m4s.lr.repair.test.ui.adapter.DeviceReplayAdapter;
import hk.m4s.lr.repair.test.ui.adapter.DeviceRequestsAdapter;
import hk.m4s.lr.repair.test.ui.webview.WebViewActivity;
import hk.m4s.lr.repair.test.utils.ToastUtil;
import hk.m4s.lr.repair.test.views.listview.VListView;
import okhttp3.Response;

/**
 * Created by qi.wang on 2017/3/27.
 * 业务回复
 */

public class DeviceReplayActivity extends UeBaseActivity implements VListView.IXListViewListener,OnItemClickListener {
    private Context context;
    private LayoutInflater inflater;
    private VListView vlist;
    private TextView device_id, device_type, device_state, device_user, device_phone, device_address;
    private List<DeviceRepalyModel> newsList = new ArrayList<>();
    private DeviceReplayAdapter replayAdapter;
    private int pageNum = 0;
    private int pageSize = 10;
    private NoticeDeviceModel model;
    private int select=1;
    String type;
    String id;
    String phone;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        baseSetContentView(R.layout.activity_device_replay_layout);
        context = this;
        hiddenFooter();
        showGoBackBtn();
        showDelete();
        model = (NoticeDeviceModel) getIntent().getSerializableExtra("model");
        setTitleText("业务回复");
        findBaseView();
    }

    void findBaseView() {
        device_id = (TextView) findViewById(R.id.device_id);
        device_type = (TextView) findViewById(R.id.device_type);
        device_state = (TextView) findViewById(R.id.device_state);
        device_user = (TextView) findViewById(R.id.device_user);
        device_phone = (TextView) findViewById(R.id.device_phone);
        device_address = (TextView) findViewById(R.id.device_address);
        vlist = (VListView) findViewById(R.id.vlist);
        vlist.setXListViewListener(this);
        replayAdapter = new DeviceReplayAdapter(DeviceReplayActivity.this, newsList);
        vlist.setAdapter(replayAdapter);
        if (model != null) {
            device_id.setText(model.getOrderNum());
            device_type.setText(model.getBusinessType());
            device_user.setText(model.getContact());
            phone=model.getContactPhone();
            device_phone.setText(model.getContactPhone());
            device_address.setText(model.getAddressInfo());
            if (model.getState().equals("3")) {
                hiddenDeleteBtn();
                device_state.setText("已完成");
            }else if(model.getState().equals("-1")){
                device_state.setText("回复中");
                showDelete();
            }else if(model.getState().equals("1")){
                device_state.setText("已回复");
                showDelete();
            }else if(model.getState().equals("2")){
                device_state.setText("已取消");
                showDelete();
            }
            getData("1");
        }
        getDeleteBtn().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                select=1;
                new AlertView("系统提示", "确认取消任务吗?", "取消", new String[]{"确定"}, null, DeviceReplayActivity.this, AlertView.Style.Alert, DeviceReplayActivity.this).setCancelable(true).show();

            }
        });
    }
    @Override
    public void onItemClick(Object o, int position) {
        //判断是否是拓展窗口View，而且点击的是非取消按钮
        if (position == AlertView.CANCELPOSITION) {
            return;
        }
         if (position == 0) {
             if(select==1) {
                 businessOperation("3", model.getId());
             }else if(select==2){
                 businessOperation(type,id);
             }else if(select==3){
                 if(!(phone==null||phone.equals(""))){
                     if (ContextCompat.checkSelfPermission(((Activity) context),
                             Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                         // 没有获得授权，申请授权
                         if (ActivityCompat.shouldShowRequestPermissionRationale(((Activity) context),
                                 Manifest.permission.CALL_PHONE)) {
                             // 返回值：
//                          如果app之前请求过该权限,被用户拒绝, 这个方法就会返回true.
//                          如果用户之前拒绝权限的时候勾选了对话框中”Don’t ask again”的选项,那么这个方法会返回false.
//                          如果设备策略禁止应用拥有这条权限, 这个方法也返回false.
                             // 弹窗需要解释为何需要该权限，再次请求授权
                             // 帮跳转到该应用的设置界面，让用户手动授权
                             Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                             Uri uri = Uri.fromParts("package", context.getPackageName(), null);
                             intent.setData(uri);
                             context.startActivity(intent);
                         } else {
                             // 不需要解释为何需要该权限，直接请求授权
                             ActivityCompat.requestPermissions(((Activity) context),
                                     new String[]{Manifest.permission.CALL_PHONE},
                                     1);
                         }
                     } else {
                         Intent phoneIntent = new Intent("android.intent.action.CALL", Uri.parse("tel:" +phone));
                         context.startActivity(phoneIntent);
                     }
                 }else{
                     ToastUtil.toast(context,"电话不正确");
                 }
             }
        }

    }
    private void onLoad() {
        vlist.stopRefresh();
        vlist.stopLoadMore();
        Date data = new Date(System.currentTimeMillis());
        vlist.setRefreshTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
                Locale.CHINA).format(data));
    }

    @Override
    public void onRefresh() {
        // TODO Auto-generated method stub
        // getData();
        vlist.setPullLoadEnable(true);
        pageNum = 0;
        getData("1");
    }

    @Override
    public void onLoadMore() {
        // TODO Auto-generated method stub
        vlist.setPullRefreshEnable(true);
        pageNum++;
        getData("2");
    }

    public void getData(final String refreshType) {
        Map<String, Object> parmas = new HashMap<>();
        parmas.put("device_type", Constant.device_type);
        parmas.put("token", SharedPreferencesUtils.getSharedPreferences(Constant.token, ""));
        try {
            JSONObject jsondata = new JSONObject();
            jsondata.put("pageNum", pageNum);
            jsondata.put("pageSize", pageSize);
            jsondata.put("type", model.getType());
            jsondata.put("id", model.getId());
            parmas.put("jsonText", jsondata.toString());
        } catch (JSONException e) {

        }
        DeviceListervice.businessRreplyList(context, parmas, new ResponseCallback<DeviceRepalyModelResult>() {
            @Override
            public void onSuccess(DeviceRepalyModelResult deviceModelResult) {
                onLoad();
                switch (refreshType) {
                    case "1":
                        newsList.clear();
                        if (deviceModelResult.getList() != null) {
                            newsList.addAll(deviceModelResult.getList());
                            if (deviceModelResult.getList().size() <= pageSize) {
                                vlist.removeFooterView();
                                vlist.setPullLoadEnable(false);
                            } else {
                                vlist.showFooterView();
                                vlist.setPullLoadEnable(true);
                            }
                        }
                        break;
                    case "2":
                        newsList.addAll(deviceModelResult.getList());
                        if (deviceModelResult.getList().size() <= pageSize) {
                            vlist.removeFooterView();
                            vlist.setPullLoadEnable(false);
                        }
                        break;
                }
                replayAdapter.notifyDataSetChanged();
            }

            @Override
            public void onError(Response response, int errorCode, String errorMsg, Exception e) {

            }
        });
    }
    public void showTips(final String type, final String id,final String price){
        this.type=type;
        this.id=id;
        select=2;
        new AlertView("提示", price, "取消", new String[]{"确定"}, null, DeviceReplayActivity.this, AlertView.Style.Alert, DeviceReplayActivity.this).setCancelable(true).show();
    }
    public void businessOperation(final String type, final String id) {
        Map<String, Object> parmas = new HashMap<>();
        parmas.put("device_type", Constant.device_type);
        parmas.put("token", SharedPreferencesUtils.getSharedPreferences(Constant.token, ""));
        try {
            JSONObject jsondata = new JSONObject();
            if (type.equals("3")) {
                jsondata.put("businessType", model.getType());
            }
                jsondata.put("type", type);
            jsondata.put("id", id);
            parmas.put("jsonText", jsondata.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        DeviceListervice.businessOperation(context, parmas, new ResponseCallback<Map>() {
            @Override
            public void onSuccess(Map deviceModelResult) {
               finish();
            }

            @Override
            public void onError(Response response, int errorCode, String errorMsg, Exception e) {

            }
        });
    }
    public void onClick(View view){
        switch (view.getId()){
            case R.id.phoneLayout:
                select=3;
                new AlertView("提示", "是否要拨打电话", "取消", new String[]{"确定"}, null, DeviceReplayActivity.this, AlertView.Style.Alert, DeviceReplayActivity.this).setCancelable(true).show();
                break;
        }
    }
    public void callPhone(String callPhone){
        select=3;
        phone=callPhone;
        new AlertView("提示", "是否要拨打电话", "取消", new String[]{"确定"}, null, DeviceReplayActivity.this, AlertView.Style.Alert, DeviceReplayActivity.this).setCancelable(true).show();
    }
}
